// 引入服务端http/https请求模块
const request = require("request");
const crypto = require("crypto");
const path = require("path");
const fs = require("fs");

// 1）获取接口密钥APIKey 和 APISecret。
const apiKey = process.env.APIKey;
const apiSecret = process.env.APISecret;
const appId = process.env.APPID;

function faceContrast(img1, img2) {
  // 2）参数authorization base64编码前（authorization_origin）的格式如下。
  // api_key="$api_key",algorithm="hmac-sha256",headers="host date request-line",signature="$signature"

  // 3）signature的原始字段(signature_origin)规则如下。 host: $host\ndate: $date\n$request-line
  const date = new Date().toGMTString(); // 获取GMT时间
  const signature_origin = `host: api.xf-yun.com\ndate: ${date}\nPOST /v1/private/s67c9c78c HTTP/1.1`;

  // 4）使用hmac-sha256算法结合apiSecret对signature_origin签名，获得签名后的摘要signature_sha。
  // signature_sha=hmac-sha256(signature_origin,$apiSecret)
  const hmac = crypto.createHmac("sha256", apiSecret).update(signature_origin);
  const signature_sha = hmac.digest("bytes");
  //console.log(signature_sha);
  // 5）使用base64编码对signature_sha进行编码获得最终的signature。
  const signature = signature_sha.toString("base64");
  // 6）根据以上信息拼接authorization base64编码前（authorization_origin）的字符串，示例如下。
  const authorization_base64 = `api_key="${apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;

  // 7）最后再对authorization_origin进行base64编码获得最终的authorization参数。
  let authorization = new Buffer.from(authorization_base64).toString("base64");
  // 请求体body
  let body = {
    header: {
      app_id: appId,
      status: 3,
    },
    parameter: {
      s67c9c78c: {
        service_kind: "face_compare",
        face_compare_result: {
          encoding: "utf8",
          compress: "raw",
          format: "json",
        },
      },
    },
    payload: {
      input1: {
        encoding: "jpg",
        status: 3,
        // image: parse("upload/20221122/78450279BF0AE6C6.jpg"),
        image: img1,
      },
      input2: {
        encoding: "jpg",
        status: 3,
        // image: parse("upload/20221122/78450279BF0AE6C6.jpg"),
        image: img2,
      },
    },
  };

  return new Promise((resolve, reject) => {
    // 发送请求
    request(
      {
        url: `https://api.xf-yun.com/v1/private/s67c9c78c?authorization=${authorization}&host=api.xf-yun.com&date=${date}`,
        method: "POST",
        headers: {
          "content-type": "application/json",
        },
        // http request body转JSON字符串
        body: JSON.stringify(body),
      },
      (err, res, body) => {
        if (err) {
          console.log("err", err);
          reject(err);
        }
        // console.log(body);
        let text = JSON.parse(body)?.payload?.face_compare_result?.text;
        if (text) {
          let result = new Buffer.from(text, "base64").toString();
          // console.log("result", result);
          // resu = JSON.parse(result);
          // console.log("res", typeof resu);

          resolve(JSON.parse(result));
          // if (resu.score > 0.67) {
          //   console.log("是同一个人");
          // } else {
          //   console.log("好像不是同一个人");
          // }
        } else {
          resolve(body);
        }
      }
    );
  });
}

module.exports = faceContrast;
